<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
	pageContext.setAttribute("basePath", basePath);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>PQ - 内聊版</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<%@ include file="include.jsp" %>
	<style type="text/css">
		form {
			margin:0 auto;
			margin-top:10%;
		}
	</style>
	
  </head>
  
  <body>

	<div class="content">

	</div>

	<script type="text/javascript">
		var ws = null;
		var userName = "${userName}"; //当前登录用户
		var host = "192.168.1.100:8080";
		var isOpen = false; //主窗口是否打开
		var sidx; //im主窗口index
		var slayero;
		var wsMsg;
		var wins = []; //存放当前打开的layer窗口
    	$(function(){
    		initWs();
    	});

    	function initWs(){
    		//页面打开后,连接socket
        	var target = "ws://"+host+"/pwtchat/echo?userName="+userName;

            if ('WebSocket' in window) {
                ws = new WebSocket(target);
                console.log("WebSocket 请求成功");
            } else if ('MozWebSocket' in window) {
                ws = new MozWebSocket(target);
                console.log("MozWebSocket 请求成功");
            } else {
                alert('WebSocket is not supported by this browser.');
                return;
            }
            
            
            //注册接收消息监听方法
            ws.onmessage = function(event){
            	console.log(event);
            	wsMsg = eval("("+event.data+")"); 
            	var type = wsMsg.type;
            	if(!isOpen){
                    //显示im主窗口
                    isOpen = true;
                  	showIm(wsMsg); 
            	}else{
            		//更新好友上线或下线
            		if("online" == type || "offline" == type){
            			var imWin = window[slayero.find('iframe')[0]['name']];
            			imWin.updateFirendGroup(wsMsg.users);
            		}
            	}
            	
            	
            	//好友消息接收
            	if(undefined != wsMsg.content && "message" == type){
             		console.log(wsMsg);
             		var from = wsMsg.from;
					var idx = getLayerIdx(from); 
            		var body = layer.getChildFrame('body', idx); 
            		if(undefined != body){
	            		var $show = body.find("#msg-show");
	            		if(undefined != $show && $show.length> 0){
	            			var msg = {
	            				nickname: from,
	            				msg: wsMsg.content,
	            				time: FY.getFormatLongDate(new Date())
	            			};
	            			
		            		$show.append(getMsgTemplate(msg));
		            		//滚动条保持底部
		            		$show.scrollTop( $show[0].scrollHeight );
	            		}
            		}
            	}

            };
            
            
            ws.onclose = function (event) {
            	console.log(event);
            }; 
            

    	};
    	
    	
    	//发送一条消息
    	function wsSend(msgs){
    		ws.send(JSON.stringify(msgs));
    	}
    	
    	/* 显示主窗口 */
	    function showIm(msg){
	     	return layer.open({
	    		  type: 2,
	    		  id: "im-main",
	    		  title: ['PQ - 内聊版', 'font-size:14px;'],
	    		  area: ['270px', '430px'],
	    		  fix: false, //不固定
	    		  maxmin: true,
	    		  shade :0.1,
	    		  content: "chat/chat-main-template.jsp",
		  		  success: function(layero, index){
		  			var win = {
		  				name: "im-main",
		  				idx: index
		  			};
		  			wins.push(win);
		  			slayero = layero;
		  			sidx = index;
			  	  },
	    		  end: function(){
	    			  window.location.href= "login.jsp";
	    		  }
	    	}); 
	    };
	    
	    
	    /* 显示聊天窗口 */
		function showMsgWindow(user){
	    	if(userName == user.nickname){
	    		FY.alert({
	    			type: "warning",msg : "跟自家自儿发消息就没意思了!"
	    		});
	    		return false;
	    	}
	    	
			var smidx = layer.open({
		  		  type: 2,
		  		  id: user.nickname,
		  		  title: ['PQ - 内聊版', 'font-size:14px;'],
		  		  area: ['450px', '370px'],
		  		  fix: false, //不固定
		  		  maxmin: false,
		  		  shade :0,
		  		  content: 'chat/chat-msg-template.jsp',
		  		  success: function(layero, index){
			  			var win = {
			  				name: "im-msg",
			  				idx: index,
			  				user: user.nickname == null ? "pwt_" : user.nickname
			  			};
			  			wins.push(win);	console.log(wins);			  
		  			  
		  		  	  	var body = layer.getChildFrame('body', index);
		  		  	  	
		  		  	  	//更新当前用户信息
		  		  	  	body.find("#nickname").text(user.nickname);
		  		  		body.find("#signature").text(user.signature);
		  		  		
		  		  		//动态绑定send事件
		  		  		body.find("#msg-send").bind("click",function(){
			  				var $inp = body.find("#msg-input"); 
			  				var msg = $inp.text();
			  				if(msg){
			  					var msgs = {
			  						layer: index,
			  						msg: msg,
			  						to: user.nickname
			  					};
			  					//提交给socket
			  					wsSend(msgs); 
			  					
			  					//显示在自己的界面上
			  					var msg = {
			  						nickname : userName,
			  						msg: msg,
			  						time: FY.getFormatLongDate(new Date())
			  					};
			  					
			  					
			  					var $show = body.find("#msg-show");
			  					$show.append(getMsgTemplate(msg));
			  					$show.scrollTop($show[0].scrollHeight );
			  					//清空输入框
			  					$inp.text("");
			  				}
		  		  	});
		  		  },
		  		  end: function(){
		  			removeLayerWin(smidx);
		  		  }
	  		}); 
		};
    
		
		
		
		function getMsgTemplate(msg){
			var html="";
			if(msg){
				html+="<div class='msg-item'>"+
					  "	<div class='msg-title'>"+
					  "		<img class='mt-face' alt='' src='${basePath}images/face.jpg'>"+
					  "		<div class='mt-name'>"+
					  "			<span class='nickname'>"+msg.nickname+"</span>"+
					  "			<span class='datetime'>"+msg.time+"</span>"+
					  "		</div>"+
					  " </div>"+
					  "	<div class='msg-content'>"+msg.msg+"</div>"+
					  "</div>";	
			}
			return html;
		}
		
		
		/* 根据用户信息获取layer的index  */
		function getLayerIdx(user){
			var idx = -1;
			if(FY.isEmpty(user)){
				return;
			}
			for(w in wins){
				if(wins[w].user == user){
					return wins[w].idx;
				}
			}
			return idx;
		}
		
		
		/* 关闭窗口时删除wins中的窗口信息 */
		function removeLayerWin(smidx){
			if(FY.isEmpty(smidx)){
				return;
			}
			for(w in wins){
				if(wins[w].idx == smidx){
					wins.splice(w,1);
				}
			}
		}
		
		
		
    </script>
  </body>
</html>
